package net.interfax.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.interfax.FaxItem;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @see http://www.interfax.net/en/dev/webservice/reference/faxstatus
 * @author DL
 */
public class FaxStatusResponse implements XmlDeserializable {
	public FaxStatusResponse() {}
	
	/**
	 * Total number of transactions for this user (regardless of number of
	 * transactions returned).
	 */
	public int totalCount;
	

	/** Total number of transactions actually returned by the query (size of faxItems array). */ 
	public int listSize;
	
	/**
	 * 0= OK; less than 0 = Error.
	 * @see http://www.interfax.net/en/dev/webservice/reference/web-service-return-codes
	 */
	public int resultCode;
	
	/** Array of FaxItem. */
	public List<FaxItem> faxItems;
	
	@Override
	public void fromXml(Node node) {
		final NodeList childNodes = node.getChildNodes();
		
		final int numChildNodes = childNodes.getLength();
		final Map<String, String> values = new HashMap<String, String>(numChildNodes);
		NodeList faxItemNodes = null;
		for (int i = 0; i < numChildNodes; ++i) {
			final Node childNode = childNodes.item(i);
			final String childNodeName = childNode.getNodeName();
			
			if (childNodeName.equals("FaxStatusResult")) {
				faxItemNodes = childNode.getChildNodes();
			} else {
				values.put(childNodeName, childNode.getTextContent());
			}
		}
		
		totalCount = Integer.parseInt(values.get("TotalCount"));
		listSize = Integer.parseInt(values.get("ListSize"));
		resultCode = Integer.parseInt(values.get("ResultCode"));

		if (faxItemNodes != null) {
			final int numFaxItems = faxItemNodes.getLength();
			faxItems = new ArrayList<FaxItem>(numFaxItems);
			for (int i = 0; i < numFaxItems; ++i) {
				final FaxItem faxItem = new FaxItem();
				faxItem.fromXml(faxItemNodes.item(i));
				faxItems.add(faxItem);
			}
		} else {
			faxItems = Collections.emptyList();
		}
	}
}
